package net.wicp.tams.common.metrics.annotation;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;

import com.codahale.metrics.Gauge;
import com.codahale.metrics.Metric;

import net.wicp.tams.common.Conf;
import net.wicp.tams.common.metrics.core.TsMetricAbstractGroup;
import net.wicp.tams.common.metrics.utility.TsLogger;

@Configuration
@Order(Ordered.LOWEST_PRECEDENCE)
public class MetricsConfig {
	// 创建组
	@Bean
	public TsMetricAbstractGroup metrics() {
		System.setProperty(TsLogger.ENV_FILE_NAME, Conf.get("common.metrics.sink.json.env_file_name"));
		System.setProperty(TsLogger.ENV_FILE_ROOT, Conf.get("common.metrics.sink.json.env_file_root"));
		return new TamsMetricAbstractGroup(Conf.get("common.metrics.sink.json.serviceName"));
	}

	private class TamsMetricAbstractGroup extends TsMetricAbstractGroup {
		@SuppressWarnings("unchecked")
		@Override
		public <T> Gauge<T> newGauge(Gauge<T> gauge, Class<?> tClass, String metricUniqMark) {
			Gauge<T> newGauge = null;
			try {
				newGauge = super.newGauge(gauge, tClass, metricUniqMark);
			} catch (Throwable e) {
				String name = metricName(tClass, metricUniqMark);
				final Metric metric = super.getMetrics().getMetrics().get(name);
				newGauge = (Gauge<T>) metric;
			}
			return newGauge;
		}

		public TamsMetricAbstractGroup(String serviceName) {
			super(serviceName);
		}
	}
}
